import { loginIn } from '@/api/userCenter/authority/account'
import { LoginRequest } from '@/api/userCenter/authority/model/accountModel'
import { AccountInfo } from '@/api/userCenter/authority/model/accountModel'
import { ActionTree } from 'vuex'
import { AccountState } from '.'
import { State } from '..'
import { AugmentActionContext } from '../types'
import { AccountMutations, AccountMutationTypes } from './mutations'
import config from '@/config'
import { message } from 'ant-design-vue'
import router from '@/router'
import { initRoute } from '@/router/initRoute'

export enum AccountActionTypes {
  /**
   * 登录
   */
  LOGIN = 'LOGIN',
  /**
   * 获取对应用户下的菜单
   */
  LOGIN_OUT = 'LOGIN_OUT',
  // FETCH_USER_ROUTE = 'FETCH_USER_ROUTE'
}

export type AccountAugmentActionContext = AugmentActionContext<
  AccountState,
  AccountMutations,
  AccountActions
>
export type LoginFormParams = Omit<LoginRequest, 'clientId' | 'secret'>

export interface AccountActions {
  [AccountActionTypes.LOGIN]: (
    ctx: AccountAugmentActionContext,
    payLoad: LoginFormParams
  ) => Promise<AccountInfo>
  [AccountActionTypes.LOGIN_OUT]: (
    ctx: AccountAugmentActionContext
  ) => Promise<void>
  // [AccountActionTypes.FETCH_USER_ROUTE]: (ctx: AccountAugmentActionContext, payLoad: any) => Promise<MenuItem[]>
}

const actions: ActionTree<AccountState, State> & AccountActions = {
  /**
   * 登录流程
   * 1. 调用登录接口获取账户信息
   * 2. 保存账户信息至 vuex & localstorage
   * 3. 根据用户信息调用菜单获取接口
   * 4. 保存菜单信息至 vuex & localstorage
   */
  LOGIN: async (ctx, payLoad) => {
    const loginParams: LoginRequest = {
      ...payLoad,
      clientId: config.clientId,
      secret: config.secret,
    }
    const resData = await loginIn(loginParams)
    // 判断是否有权限进入系统
    if (!resData.data.perms) {
      message.error('当前用户不允许进入系统，请联系管理员配置相应权限')
      throw new Error('当前用户不允许进入系统，请联系管理员配置相应权限')
    }
    ctx.commit(AccountMutationTypes.SAVE_ACCOUNT_INFO, resData.data)

    return new Promise((resolve) => {
      resolve(resData.data)
    })
  },
  LOGIN_OUT: async (ctx) => {
    ctx.commit(AccountMutationTypes.DELETE_ACCOUNT_INFO)
    ctx.commit(AccountMutationTypes.DELETE_MENU_LIST)
    initRoute.forEach((item) => {
      router.addRoute(item)
    })
    router.push('/login')
  },
  // FETCH_USER_ROUTE: async (ctx, payLoad) => {
  //   const resData = await fetchMenuList()
  //   ctx.commit(AccountMutationTypes.SAVE_MENU_LIST, resData.data)

  //   return new Promise(resolve => {
  //     resolve(resData.data)
  //   })
  // }
}

export default actions
